package club.janna.hello.factory;

import club.janna.hello.annotation.Mappable;
import club.janna.hello.annotation.PositionNo;
import club.janna.hello.util.DataConvertor;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public  class DeviceFactory{
    /**
     * 生成实例对象
    * */
    public static <T> T generate(Class<T> t){
        try {
            return t.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成实例对象
     * */
    public static <T> T generate(Map<Integer, Float> data, String tempStr, Class<T> t){
        if(t == null || data == null || data.isEmpty())
            return null;
        if(t.getAnnotation(Mappable.class) == null)
            throw new RuntimeException("your class can not be mapping!");
        int[] temp = DataConvertor.commaSeparationString2IntArray(tempStr);
        if(temp == null || temp.length == 0)
            return null;
        T result = null;
        try {
            result = t.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if(result == null)
            return null;
        Field[] fields = t.getDeclaredFields();
        if(fields != null)
            for(Field field : fields)
                if(field != null) {
                    PositionNo no = field.getAnnotation(PositionNo.class);
                    if(no != null && no.value() >= 0 && no.value() < temp.length && temp[no.value()] != -1) {
                        try {
                            field.setAccessible(true);
                            field.setFloat(result, data.get(temp[no.value()]));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
        return result;
    }


    /**
     *@param sourceMap 待解析数据
     *@param templateMap 解析模板
     *@return 返回map
     */
    public static Map parseMap(Map<Integer, Float> sourceMap,Map templateMap){
        Map reMap = new HashMap();
        for (Map.Entry<Integer, Float> entry : sourceMap.entrySet()) {
            System.out.println("key= " + entry.getKey().toString() + " and value= " + entry.getValue());
            if(templateMap.containsKey(entry.getKey()+"")){
                reMap.put(templateMap.get(entry.getKey().toString()),entry.getValue());
            }
        }
        return reMap;
    }

}
